//
//  CZEmoticonToolBar.swift
//  keyBoard
//
//  Created by 李伟鹏 on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

protocol CZEmoticonToolBarDelegate: NSObjectProtocol {
    // 2.定义协议方法
    func didSelectButtonType(didSelectedType: CZEmoticonToolBarType)
}

enum CZEmoticonToolBarType: Int {
    case Recent     // 最近
    case Default    // 默认
    case Emoji      // emoji
    case Lxh        // 浪小花
}

class CZEmoticonToolBar: UIView {

    weak var delegate: CZEmoticonToolBarDelegate?
    
    private var selectedButton: UIButton?
    
    private var buttons = [UIButton]()
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.lightGrayColor()
        let titles = ["最近", "默认", "emoji", "浪小花"]
        var index = 0
        for title in titles{
            let button = UIButton()
            button.setTitle(title, forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_normal"), forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_selected"), forState: UIControlState.Highlighted)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_selected"), forState: UIControlState.Selected)
            button.tag = index
            button.addTarget(self, action: "didClickButton:", forControlEvents: UIControlEvents.TouchUpInside)
            self.addSubview(button)
            buttons.append(button)
            index++
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let buttonWidth = self.frame.width / CGFloat(buttons.count)
        var index = 0
        for button in buttons{
            let frame = CGRect(x: CGFloat(index) * buttonWidth, y: 0, width: buttonWidth, height: self.frame.height)
            button.frame = frame
            index++
        }
        let defaultButton = buttons[0]
        switchSelectedButton(defaultButton)
    }
    
    @objc private func didClickButton(button: UIButton){
        let type = CZEmoticonToolBarType(rawValue: button.tag)!
        switchSelectedButton(button)
        
        delegate?.didSelectButtonType(type)
        
    }
    
    func switchSelectedButtonWitchSection(section: Int){
        let button = buttons[section]
        switchSelectedButton(button)
    }
    
    private func switchSelectedButton(button: UIButton){
        if button == selectedButton{
            return
        }
        selectedButton?.selected = false
        button.selected = true
        selectedButton = button
    }

}
